import re
from django.contrib.auth.backends import ModelBackend

from apps.users.models import User


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            if re.match(r'1[3-9]\d{9}',username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None

        #校验user是否存在并校验密码是否正确
        if user.check_password(password) and self.user_can_authenticate(user):
            return user




